/**
* 核心类库
 */

var t = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (t) {
  return typeof t
}
  : function (t) {
    return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t
  },
  e = require("check");
module.exports = {
  toQueryPair: function (t, e) {2
    return void 0 === e ? t : t + "=" + encodeURIComponent(null === e ? "" : String(e))
  },
  /*
  *处理请求路径
  * @param n 方法名
  * @param o 参数
  * return  string
  */
  getUrl: function (n, o) {
   var n = n.replace(/\//gi, "/");
    var a = getApp().globalData.api + "api/" + n;
    //lujin
    return o && ("object" == (void 0 === o ? "undefined" : t(o)) ? a += "?app_id=" + getApp().globalData.appid +"&" + e.param(o) : "string" == typeof o && (a += "&" + o)),
      a
  },
    /*
     *处理请求路径格式
     * @param t:缓存值
     * @param n:data参数
     * @param o:success后返回值
     * @param a:请求类型
     * return  string
     */
  json: function (t, n, o, i, a, c) {
    var r = getApp(),
      s = r.getCache("userinfo"),
     d = r.requirejs("core");
    i && d.loading()
    var p = a ? this.getUrl(t) : this.getUrl(t, n),
      l = {
        url: p,
        method: a ? "POST" : "GET",
        header: {
          "Content-type": a ? "application/x-www-form-urlencoded" : "application/json",
        }
      };
    a && (l.data = e.param(n)),//参数
      o && (l.success = function (t) {
        i && d.hideLoading();
        if (t.errMsg == "request:ok"){
          if (typeof (t.data) == "string") {
            if (t.data.indexOf("html") >= 0 && t.data.indexOf("head") >= 0 && t.data.indexOf("body") >= 0) {
              d.error('服务器错误！');
              return;
            }
          }
          "function" == typeof o, o(t.data)
        }else{
          this.alert(t.errMsg)
        }
         
      }),
        l.fail = function (t) { that.alert(t.errMsg)};
      wx.request(l)
     console.log(l)
  },
  /*
  *post请求
  * @param n 方法名
  * return  string
  */
  post: function (t, e, n, i) {
    var that = this;
    var name = t.split('/');
    name = name[0] + '_' + name[1];
    //console.log(name)
    i && that.loading();
    e.v = getApp().version;
    getApp().util.request({
      'url': 'entry/wxapp/' + name,
      data: e,
      method:'POST',
      success: function (t) {
        i && that.hideLoading();
        if (t.errMsg == "request:ok") {
          if (typeof (t.data) == "string") {
            if (t.data.indexOf("html") >= 0 && t.data.indexOf("head") >= 0 && t.data.indexOf("body") >= 0) {
              // that.error('请求异常');
              return;
            }
          }
          if (t.data == '') {
            // that.error('请求异常！');
            return;
          }
          //转json对象
          var res_data = t.data;
           // console.log(res_data)
          if (typeof res_data == 'string') {
            console.log(typeof res_data)
            res_data = that.json_parse(res_data);
          }
          "function" == typeof n, n(res_data)
        } else {
          //that.alert(t.errMsg)
         //that.alert('网络连接超时');
        }
      },
      fail: function (res) {
        //that.alert(res.errMsg);
        that.alert('网络连接超时');
      }
    }); 
   // this.json(t, e, n, o, true, i)
  },
  card_path: function (param,page){
    page=page||"1";
    var b = getCurrentPages()[0]["route"];
    if(page!="1"){
      b+=page;
    }
    var c=0;
    for(var k in param){
      if(c==0){
        b+="?"+k+"="+param[k];
      }else{
        b+="&"+k+"="+param[k];
      }
      c++;
    }
    return b;
  },

   /*
    * get请求
    * @param n 方法名
    * return  string
    */
  get: function (t, e, n, i) {
    var that=this;
    var name=t.split('/');
     name=name[0]+'_'+name[1];
    //  console.log(name)
     i && that.loading();
    getApp().util.request({
      'url': 'entry/wxapp/' + name,
      data:e,
      success: function (t) {
        i && that.hideLoading();
        if (t.errMsg == "request:ok") {
          if (typeof (t.data) == "string") {
            if (t.data.indexOf("html") >= 0 && t.data.indexOf("head") >= 0 && t.data.indexOf("body") >= 0) {
              // that.error('请求异常');
              return;
            }
          }
          if(t.data==''){
            //that.error('请求异常！');
            console.log('请求异常！');
            return;
          }
          //转json对象
          var res_data = t.data;
          //  console.log(res_data+name)
          if (typeof res_data == 'string') {
            // console.log(typeof res_data)
            res_data = that.json_parse(res_data);
          }

          "function" == typeof n, n(res_data)
        } else {
          //that.alert(t.errMsg)
         // that.alert('网络连接超时');
        }
      },
      fail: function (res) {
        i && that.hideLoading();
        //console.log("failed",res.errMsg.indexOf("domain list"))
        if (res.errMsg.indexOf("domain list") > 0) {
          that.alert('请在小程序后台配置服务器域名');
        } else {
          that.alert(res.errMsg);
        }
      }
    });
  },

  alert: function (e, n) {
    "object" === (void 0 === e ? "undefined" : t(e)) && (e = JSON.stringify(e)),
      wx.showModal({
        title: "提示",
        content: e,
        showCancel: false,
        success: function (t) {
          t.confirm && "function" == typeof n && n()
        }
      })
  },
  confirm: function (e, n, o) {
    "object" === (void 0 === e ? "undefined" : t(e)) && (e = JSON.stringify(e)),
      wx.showModal({
        title: "提示",
        content: e,
        showCancel: true,
        success: function (t) {
          t.confirm ? "function" == typeof n && n() : "function" == typeof o && o()
        }
      })
  },
  loading: function (t) {
    void 0 !== t && "" != t || (t = "加载中"),
      wx.showToast({
        title: t,
        icon: "loading",
        duration: 5e6
      })
  },
  hideLoading: function () {
    wx.hideToast()
  },
  toast: function (t, e) {
    e || (e = "loading"),
      wx.showToast({
        title: t,
        icon: e,
        duration: 1000
      })
  }, 
  warning:function(t){
    wx.showToast({
      title: t,
      image: "/yb_mingpian/static/images/icon-warning.png",
      duration: 2000
    })
  },
  error: function (t) {
    wx.showToast({
      title: t,
      icon: 'success',
      image: "/yb_mingpian/static/images/x.png",
      duration: 2000
    })
  },
  success: function (t) {
    wx.showToast({
      title: t,
      icon: "success",
      duration: 1000
    })
  },
  //event.currentTarget返回绑定事件的元素
  pdata: function (t) {
    return t.currentTarget.dataset
  },
  //event.target返回触发事件的元素
  data: function (t) {
    return t.target.dataset
  },
  phone: function (t) {
    var e = this.pdata(t).phone;
    wx.makePhoneCall({
      phoneNumber: e
    })
  },
  /**
   * 时间戳转时间字符串
   */
  time_format:function(time){
    var timestamp = time;
    var d = new Date(timestamp * 1000);    //根据时间戳生成的时间对象
    var date = (d.getFullYear()) + "-" +
      (d.getMonth() + 1) + "-" +
      (d.getDate()) + " " +
      (d.getHours()) + ":" +
      (d.getMinutes()) + ":" +
      (d.getSeconds());
    return date;
  },
  /**
  * 时间字符串转时间戳
  */
  time_str: function (date) {
    date = date.substring(0, 19);
    date = date.replace(/-/g, '/');
    var timestamp = new Date(date).getTime();
    return timestamp/1000;
  },
  /**
   * 倒计时
   */
  Countdown: function (time, obj,k=0,old=-1) {
    var e = {
      countDownDay : 0,
      countDownHour: 0,
      countDownMinute: 0,
      countDownSecond: 0,
    },
        fs=[],
        interval = 'interval'+k,
        olds = 'interval' + old,
        shows = 'interval' + k,
        totalSecond = time - Date.parse(new Date()) / 1000;
    fs[shows]=e;
    console.log("22222",interval);
    clearInterval(olds);
    if(old>=0){
        clearInterval(olds);
    }
    if (totalSecond <= 0) {
      fs[shows].show_time = false;
      typeof obj == "function" & obj(fs[shows])
    } else {
      clearInterval(interval);
       interval = setInterval(function () {
        // 秒数  
        var second = totalSecond;

        // 天数位  
        var day = Math.floor(second / 3600 / 24);
        var dayStr = day.toString();
        if (dayStr.length == 1) dayStr = '0' + dayStr;

        // 小时位  
        var hr = Math.floor((second - day * 3600 * 24) / 3600);
        var hrStr = hr.toString();
        if (hrStr.length == 1) hrStr = '0' + hrStr;

        // 分钟位  
        var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
        var minStr = min.toString();
        if (minStr.length == 1) minStr = '0' + minStr;

        // 秒位  
        var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
        var secStr = sec.toString();
        if (secStr.length == 1) secStr = '0' + secStr;
        fs[shows].countDownDay = dayStr,
          fs[shows].countDownHour = hrStr,
          fs[shows].countDownMinute = minStr,
          fs[shows].countDownSecond = secStr,
          typeof obj == "function" && obj(fs[shows])
        totalSecond--;
        if (totalSecond < 0) {
          clearInterval(interval);
          wx.showToast({
            title: '活动已结束',
          });
          fs[shows].countDownDay = "0",
            fs[shows].countDownHour = "0",
            fs[shows].countDownMinute = "0",
            fs[shows].countDownSecond = "0",
            fs[shows].show_time = false;
          typeof obj == "function" && obj(fs[shows])
        }
      }.bind(this), 1000);
    }

  },
  /**
 * json字符串转对象
 */
  json_parse: function (str) {
    var jsonStr = str;
    jsonStr = jsonStr.replace(" ", "");
    if (typeof jsonStr != 'object') {
      jsonStr = jsonStr.replace(/\ufeff/g, "");//重点
      var obj = JSON.parse(jsonStr);
      return obj
    }
  },
 
  /**
   * 对象转json字符串
   */
  str:function(obj){
   var aToStr = JSON.stringify(obj);
   return aToStr;
  },
  /**
   * 腾讯地图
   * lat 纬度
   * lng 经度
   * address 地址名称
   * name 公司名称
   */
  tx_map: function (lat, lng, address, name = '') {
    lat = parseFloat(lat);
    lng = parseFloat(lng);

    var that = this;
        //cache = getApp().getCache("map");

    if (lat && lng) {
      wx.openLocation({
        latitude: lat,
        longitude: lng,
        scale: 18,
        address: address,
        name: name
      })
    } else {
      wx.getLocation({
        type: 'gcj02',
        success: function (res) {
          console.log(res)
          getApp().setCache("map", res, 1200);
          var latitude = res.latitude
          var longitude = res.longitude
          wx.openLocation({
            latitude: lat,
            longitude: lng,
            scale: 18,
            address: address,
            name: name
          })
        },
        fail: function () {
          that.alert('未授权位置信息')
        }
      })
    }
  },
  /**
    * 图片预览
    * url str 当前图片路径
    * arr json字符串
    * field arr中图片路径的字段名
    */
  previewImage: function (url, arr, field) {
    var urls=[];
    arr = JSON.parse(arr);
    arr.forEach(function (t, k) {
      urls[k] = t[field];
    });
    wx.previewImage({
      current:url, // 当前显示图片的http链接
      urls: urls// 需要预览的图片http链接列表
    })
  },
  /**
   * 复制到剪贴板
   * data string
   */
  Clipboard: function (data) {
    var that = this;
    wx.setClipboardData({
      data: data,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            //that.alert('复制成功！')
          }
        })
      }
    })
  },
  //跳转
  jump:function(url,i){
      var that = this;
    (!i || i=='')?i=1:i=i;
    if(i==1){
      wx.navigateTo({
        url: url,
        fail: function (i) {
          console.log("navigateTo_fail:",i);
          console.log("tabbar:",i.errMsg.indexOf("tabbar"));
          console.log("tab bar:",i.errMsg.indexOf("tab bar"));
          if (i.errMsg.indexOf("tab bar") >= 0 || i.errMsg.indexOf("tabbar") >= 0) {
            wx.switchTab({//跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
              url: url
            })
          }
        }
      })
    }else if(i==2){
      wx.redirectTo({
        url: url
      })
    }else if(i==3){
      wx.reLaunch({//关闭所有页面，打开到应用内的某个页面。
        url: url
      })
    }else if(i==4){
      wx.switchTab({//跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
          url: url,
          fail: function (res) {
              console.log("switchTab_fail:",res);
              //that.alert('跳转失败');
          }
      })
    }else if(i==5){
      wx.navigateBack()
    }
  },
  ReName:function(e){
    wx.setNavigationBarTitle({
      title: e?e:''
    })
  },
  /**
* 定义函数removeByValue进行元素删除
* param arr 数组 
* param val 元素value值
* return arr
*/
  removeByValue: function (arr, val, obj) {
    var index = -1;
    for (var i = 0; i < arr.length; i++) {
      console.log(arr[i])
      if (arr[i] == val) {
        index = i;
        break;
      }
    }
    arr.splice(index, 1);
    typeof obj == "function" && obj(arr)
  },
  
  setting:function(){
    wx.setNavigationBarColor({
      frontColor: getApp().config.text_color,
      backgroundColor: getApp().config.nv_color,
      animation: {
        duration: 0,
        timingFunc: "easeIn"
      }
    });
  },
  //底部导航跳转小程序，web网页，内部页面
  menu_url: function (k,i=1) {
    var that_ = this;

    var data = that_.pdata(k),
        address = '',
      k=data.key,
      url = data.url ? data.url : '',
      appid = data.appid ? data.appid : '',
      path = data.path ? data.path : '',
      title = data.title ? data.title : '',
      phone = data.phone ? data.phone : '',
      lat = data.lat ? data.lat : '',
      lng = data.lng ? data.lng : '';
    console.log(data)
    if (k == 1) {
      console.log("k is 1 !!!!!!")
      if (url && url.length > 0) {
        console.log(url);
        console.log(i);
        that_.jump(url, i);
      }
    } else if (k == 2) {//跳转小程序
      wx.navigateToMiniProgram({
        appId: appid,
        path: path,
        extraData: {
          foo: 'bar'
        },
        envVersion: 'release',
        success(res) {
          console.log('打开成功')
        }
      })
    } else if (k == 3) {//web网页
      var patt = '/yb_mingpian/pages/web/index?url=' + escape(url) + '&name=' + title;
      console.log("path:"+patt);
     that_.jump(patt);
      // that_.jump(path);
    } else if (k == 4) {//打电话
      if (phone){
        wx.makePhoneCall({
          phoneNumber: phone
        })
      }else{
        that_.alert('电话不能为空');
      }
    } else if (k == 5) {//地图
      if (lat && lng){
          // 获取公司信息
          that_.get("User/About", {}, function (res) {
              if (res.code == 0) {
                  console.log(res)
                  address = res.info.address,
                      title = res.info.name
                  that_.tx_map(lat,lng,address,title);
              } else {
                  console.log("companyInfo:fail",res.msg)
              }
          })
      }else{
        that_.alert('请完善位置信息');
      }

    } else {
      return;
    }
  },
  /**
     * 设置监听器
     */
  setWatcher(data, watch) { // 接收index.js传过来的data对象和watch对象
    Object.keys(watch).forEach(v => { // 将watch对象内的key遍历
      this.observe(data, v, watch[v]); // 监听data内的v属性，传入watch内对应函数以调用
    })
  },

  /**
   * 监听属性 并执行监听函数
   */
  observe(obj, key, watchFun) {
    var val = obj[key]; // 给该属性设默认值
    Object.defineProperty(obj, key, {
      configurable: true,
      enumerable: true,
      set: function (value) {
        val = value;
        watchFun(value, val); // 赋值(set)时，调用对应函数
      },
      get: function () {
        return val;
      }
    })
  },

  // 最新倒计时
  newCountDown: function (endTimeList,that) {
    var countDownArr = [];

    // 对结束时间进行处理渲染到页面
    endTimeList.forEach(function(value,index){
      var totalSecond = value - Date.parse(new Date()) / 1000;
      var obj = null;
      // 总秒数
      var second = totalSecond;

      if (totalSecond <= 0) {
        obj = {
          countDownDay : 0,
          countDownHour: 0,
          countDownMinute: 0,
          countDownSecond: 0,
          show_time: false
        };
      } else {
        // 天数位
        var day = Math.floor(second / 3600 / 24);
        var dayStr = day.toString();
        if (dayStr.length == 1) dayStr = '0' + dayStr;

        // 小时位
        var hr = Math.floor((second - day * 3600 * 24) / 3600);
        var hrStr = hr.toString();
        if (hrStr.length == 1) hrStr = '0' + hrStr;

        // 分钟位
        var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
        var minStr = min.toString();
        if (minStr.length == 1) minStr = '0' + minStr;

        // 秒位
        var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
        var secStr = sec.toString();
        if (secStr.length == 1) secStr = '0' + secStr;

        obj = {
          countDownDay : dayStr,
          countDownHour: hrStr,
          countDownMinute: minStr,
          countDownSecond: secStr,
          show_time: true
        };
      }
      countDownArr.push(obj);
    })

    that.setData({countDownList: countDownArr})
    console.log('time',countDownArr)
  },

}